//
//  LAMerchantInformationTableView.m
//  LYLazizDevelopDemo
//
//  Created by xbn_iMac on 2016/10/25.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LAMerchantInformationTableView.h"
#import "LAMerchantDetailHeaderView.h"
#import "LZRestaurantDetailModel.h"
#import "LAMerchantInformationFirstTableViewCell.h"
#import "LAMerchantInformationSecondTableViewCell.h"
#import "LZRestaurantTableViewCell.h"
#import "LZRestaurantListModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "Masonry.h"

@interface LAMerchantInformationTableView ()<UITableViewDataSource,UITableViewDelegate>


@property (nonatomic, strong) LAMerchantInformationFirstTableViewCell *openHoursCell;
@property (nonatomic, strong) UIView *restaurantHeaderView;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@property (nonatomic, assign) BOOL isRequesting;

@end

@implementation LAMerchantInformationTableView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.separatorColor = [UIColor clearColor];
        self.backgroundColor = UIColorFromRGB(0xeeeeee, 1);

        [self registerCell];
        [self configBaseData];
        
        self.delegate = self;
        self.dataSource = self;
    
        [self createFooterView];
    }
    return self;
}

#pragma mark - Public Method

- (void)checkHaveData {
    if (self.dataArr.count == 0) {
        if (self.subTableDelegate && [self.subTableDelegate respondsToSelector:@selector(requestDateWithType:andPrameter:andPage:andLimit:resultSuccess:)]) {
            if (!self.isRequesting) {
                [self downLoadNewData];
            }
        }
    }
}

/* --------------------- configure Super Refresh method --------------------- */

- (void)downLoadNewData {
    [self requestListWithIsDownLoad:YES];
}

- (void)requestListWithIsDownLoad:(BOOL)isDownLoad {

    self.isRequesting = YES;
    
    WS(weakSelf)
    [self.subTableDelegate requestDateWithType:TableViewType_Information andPrameter:nil andPage:self.page andLimit:self.limit resultSuccess:^(NSArray *result,NSNumber *timeStemp) {
        weakSelf.isRequesting = NO;
        
        if (result) {
            
            if (isDownLoad) {
                [weakSelf.dataArr removeAllObjects];
            }
            
            if (result.count>0) {
                
                [weakSelf.dataArr addObjectsFromArray:result];

                if (result.count>5) {
                    [weakSelf.dataArr removeObjectsInRange:NSMakeRange(5, result.count-5)];
                }
                
                [weakSelf reloadData];
            }
            
        }
    }];
}

- (void)setModel:(LZRestaurantDetailModel *)model {
    _model = model;
    // 今天营业时间
    self.openHoursCell.labTitle.text = LZLocalizedString(@"restaurant_opentime", nil);
    self.openHoursCell.labContent.text = [NSString stringWithFormat:@"%@ ~ %@",model.openTime,model.closeTime];
    
    [self createHeaderView];
    [self reloadData];
}

#pragma mark - Private Method

- (void)registerCell {
    
    self.openHoursCell = [[[NSBundle mainBundle] loadNibNamed:@"LAMerchantInformationFirstTableViewCell" owner:self options:nil] firstObject];
    self.openHoursCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [self registerNib:[UINib nibWithNibName:@"LAMerchantInformationSecondTableViewCell" bundle:nil] forCellReuseIdentifier:@"AddressAndPhoneNumberCell"];
    [self registerNib:[UINib nibWithNibName:@"LZRestaurantTableViewCell" bundle:nil] forCellReuseIdentifier:@"LZRestaurantTableViewCell"];
}

- (void)configBaseData {
    self.page = 1;
    self.limit = 6;
    self.dataArr = [NSMutableArray array];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }
    
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return self.openHoursCell;
        }
        else {
            LAMerchantInformationSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressAndPhoneNumberCell"];
            if (indexPath.row == 1) {
                cell.imgIcon.image = [UIImage imageNamed:@"map_location_icon_unselect"];
                cell.labContent.text = self.model.restaurantAddress;
                cell.line.hidden = NO;
            }
            else if (indexPath.row == 2) {
                cell.imgIcon.image = [UIImage imageNamed:@"icon_手机"];
                cell.labContent.text = self.model.cellphone;
                cell.line.hidden = YES;
            }
            return cell;
        }
        
    }
    else {
        LZRestaurantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LZRestaurantTableViewCell"];
        cell.type = CellType_Normal;
        cell.isShowDistance = YES;
        cell.model = self.dataArr[indexPath.row];
        return cell;
    }
    return nil;
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return [tableView fd_heightForCellWithIdentifier:@"LZRestaurantTableViewCell" cacheByIndexPath:indexPath configuration:^(id cell) {
            
        }];
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        // 地址那一行，有可能会出现折行的情况，所以需要单独算一下高度
        CGFloat padding = 22*2;
        CGFloat labHeight = [self getTextHeightWithText:self.model.restaurantAddress Font:[UIFont systemFontOfSize:14] Width:(SCREEN_WIDTH-57)];
        return padding + labHeight;
    }
    
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 70;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return self.restaurantHeaderView;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            if (self.subTableDelegate && [self.subTableDelegate respondsToSelector:@selector(tableViewType:didSelectRowAtIndexPath:object:)]) {
                 [self.subTableDelegate tableViewType:TableViewType_Information didSelectRowAtIndexPath:indexPath object:nil];
            }
        }
        else if (indexPath.row == 2) {
            if (self.subTableDelegate && [self.subTableDelegate respondsToSelector:@selector(tableViewType:didSelectRowAtIndexPath:object:)]) {
                LAMerchantInformationSecondTableViewCell *cell = (LAMerchantInformationSecondTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
                [self.subTableDelegate tableViewType:TableViewType_Information didSelectRowAtIndexPath:indexPath object:cell.labContent.text];
            }
        }
    }
    else if (indexPath.section == 1) {
        if (self.subTableDelegate && [self.subTableDelegate respondsToSelector:@selector(tableViewType:didSelectRowAtIndexPath:object:)]) {
            LZRestaurantListModel *model = self.dataArr[indexPath.row];
            [self.subTableDelegate tableViewType:TableViewType_Information didSelectRowAtIndexPath:indexPath object:model.restaurantId];
        }
    }
}

#pragma mark - 推荐商店的headerview
- (UIView*)restaurantHeaderView {
    if (_restaurantHeaderView) {
        return _restaurantHeaderView;
    }
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    _restaurantHeaderView = view;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, CGRectGetWidth(view.bounds), 60)];
    bgView.backgroundColor = [UIColor whiteColor];
    [view addSubview:bgView];
    
    UIView *leftLine = [[UIView alloc] init];
    leftLine.backgroundColor = UIColorFromRGB(0x000000, 1);
    [bgView addSubview:leftLine];

    UILabel *lab = [[UILabel alloc] init];
    // 附近的餐厅
    lab.text = LZLocalizedString(@"restaurant_nearby", nil);
    lab.font = [UIFont systemFontOfSize:15];
    lab.textColor = UIColorFromRGB(0x333333, 1);
    [bgView addSubview:lab];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
    [bgView addSubview:line];
    
    [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(0);
        make.width.equalTo(4);
        make.height.equalTo(20);
        make.centerY.equalTo(bgView);
    }];
    
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.equalTo(bgView);
        make.leading.equalTo(bgView).offset(10);
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView);
        make.leading.equalTo(bgView).offset(10);
        make.trailing.equalTo(bgView).offset(-10);
        make.height.mas_equalTo(0.5);
    }];
    
    return _restaurantHeaderView;
}

-(void)createHeaderView {
    
    LAMerchantDetailHeaderView *headerView = [LAMerchantDetailHeaderView instanceLAMerchantDetailHeaderView];
    headerView.haveADView = NO;
    headerView.model = self.model;
    
    CGFloat headerHeight = [headerView judgeHeaderViewHeight];
    
    UIView *headerTemp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, headerHeight)];
    self.tableHeaderView = headerTemp;
    
    headerView.frame = headerTemp.bounds;
    [headerTemp addSubview:headerView];
}

- (CGFloat)getTextHeightWithText:(NSString *)text Font:(UIFont *)font Width:(CGFloat)width {
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName: font,
                                 };
    CGRect expectedLabelRect = [text boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributes
                                                  context:nil];
    return CGRectGetHeight(expectedLabelRect);
}

@end
